<?php

namespace djepo\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use djepo\UserBundle\Entity\User as User;
use djepo\UserBundle\Form\UserType;

use Symfony\Component\HttpFoundation\Response;

/**
 * User controller.
 *
 * @Route("/api/user")
 */
class UserRestController extends Controller
{
    /**
     * Lists all User entities.
     *
     * @Route("/", name="user")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('djepoUserBundle:User')->findAll();

        $serializer = $this->get('serializer'); 

       return new Response($serializer->serialize($entities  , 'json')); 
    }

    /**
     * Creates a new User entity.
     *
     * @Route("/new")
     * @Method("POST")
     * @Template()
     */
    public function newAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $jsonData = $this->get('request')->query->get('json');

        $serializer = $this->get('serializer');
        $user = $serializer->deserialize($jsonData, 'djepo\UserBundle\Entity\User', 'json');

        $qb = $em->createQueryBuilder();
        $qb->select('u');
        $qb->from('djepoUserBundle:User','u');
        $qb->where('u.email LIKE :email');
        $qb->setParameter('email',$user->getEmail());

        $total = count($qb->getQuery()->getResult());

        if($total == 1)
            return new Response($serializer->serialize($qb->getQuery()->getSingleResult()  , 'json'));

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return new Response($serializer->serialize($user  , 'json'));

    }

    /**
     * Get user products
     *
     * @Route("/currency")
     * @Method("POST")
     * @Template()
     */
    public function currencyAction()
    {
        $em = $this->getDoctrine()->getManager();
        $id = $this->get('request')->query->get('id');
        $currency = $this->get('request')->query->get('currency');
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($id);
        $user->setCurrency($currency);
        $em->persist($user);
        $em->flush();
        return new Response("OK");
    }
    
}
